package com.keat.qqserver.service;

import com.keat.qqcommon.Message;
import org.junit.jupiter.api.Test;
//import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Keat-Jie
 * @version 1.0
 */


public class OffLineMessageService {
    //key->getterId value->contents
    private static ConcurrentHashMap<String, ArrayList> offlineMap=new ConcurrentHashMap();

    public static ConcurrentHashMap<String, ArrayList> getOfflineMap() {
        return offlineMap;
    }

    public static void setOfflineMap(ConcurrentHashMap<String, ArrayList> offlineMap) {
        OffLineMessageService.offlineMap = offlineMap;
    }
    @Test

    public void test(){
        HashMap<String, String> ssHashMap = new HashMap<>();
        ssHashMap.put("string","hello");
        System.out.println(ssHashMap.containsKey("string"));

    }
    //将离线消息存入到集合中
    //编写getter不在线 并将离线消息添加到offlineMap
    public static void addOfflineMap(Message message){
        //如果getter不存在 那么创建一个ArrayList 并将message放入
        if(!offlineMap.containsKey(message.getGetter())){
            ArrayList<Message> messages = new ArrayList<>();
            messages.add(message);
            offlineMap.put(message.getGetter(),messages);
        }
        else {
            ArrayList arrayList = offlineMap.get(message.getGetter());
            arrayList.add(message);
        }
        System.out.println("离线消息已经存放在offlineMap中");

    }
    //编写方法判断user是否存在于offlineMap中 如果存在 就获取对应getter的socket 将ArrayList中的所有内容发送
    public static void sendOfflineMessage(String userId,ConcurrentHashMap offlineMap){

        if (offlineMap.containsKey(userId)){
            try {
                ArrayList<Message> arrayList = (ArrayList<Message>) offlineMap.get(userId);
                OutputStream os = ManageClientThreads.getServerConnectClientThread(userId).getSocket().getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);
                //将message集合发送到客户端
                oos.writeObject(arrayList);
                System.out.println("发送成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else System.out.println("发送失败");

    }
    //编写方法判断getter是否在线
    public static boolean isOnline(String getterId){
        HashMap<String, ServerConnectClientThread> hm = ManageClientThreads.getHm();
        return hm.containsKey(getterId);
    }
    //将离线消息从offlineMap删除
    public static void deleteOfflineMessage(String getterId){
        ArrayList remove = offlineMap.remove(getterId);
        System.out.println("删除消息成功"+remove);
    }
}


